from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from starlette.responses import HTMLResponse
from fastapi.responses import FileResponse
import os
from api.deps import app_routers

app = FastAPI(
    title='ChatBot API Docs',
    description='Chatbot > agent & LLM & MCP',
    version='1.0.0',
    docs_url='/docs',
    redoc_url='/redocs',  # 注意：你写的是 /redocs，不是 /redoc，保持一致
)

# 挂载静态文件：/static 和 /assets
# app.mount("/static", StaticFiles(directory="dist/static"), name="static")
app.mount("/assets", StaticFiles(directory="dist/assets"), name="assets")

# 允许跨域
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 包含你的 API 路由
app.include_router(app_routers)

# 提供前端 index.html 的路由


@app.get("/", response_class=HTMLResponse, include_in_schema=False)
async def serve_frontend():
    try:
        with open("./dist/index.html", "r", encoding="utf-8") as f:
            return HTMLResponse(content=f.read())
    except FileNotFoundError:
        raise HTTPException(status_code=404, detail="Frontend file not found")

@app.get("/favicon.ico", include_in_schema=False)
async def favicon():
    favicon_path = "./dist/favicon.ico"
    if not os.path.exists(favicon_path):
        raise HTTPException(status_code=404, detail="Favicon not found")
    return FileResponse(favicon_path)

# 捕获所有未匹配的 GET 路由（用于前端路由，如 /chat, /settings 等）
# 注意：必须放在最后，避免覆盖 API 路由
@app.get("/{full_path:path}", response_class=HTMLResponse, include_in_schema=False)
async def serve_frontend_fallback(full_path: str):
    # 如果请求的是 API 或文档路径，不要返回 index.html
    if full_path.startswith("api") or full_path.startswith("docs") or full_path.startswith("redocs"):
        raise HTTPException(status_code=404)

    # 如果是静态资源路径，上面的 StaticFiles 已处理，不会走到这里
    # 所以走到这里的都是前端路由（如 /chat、/login）
    try:
        with open("./dist/index.html", "r", encoding="utf-8") as f:
            return HTMLResponse(content=f.read())
    except FileNotFoundError:
        raise HTTPException(
            status_code=500, detail="Frontend index.html not found")


if __name__ == '__main__':
    import uvicorn

    uvicorn.run('main:app', host='0.0.0.0', port=8000, reload=True, workers=3)
